package com.ywcq.netty.httpserver.helloworld;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

public class StaticContentCache 
{
	
	private Map<String,StaticResource> staticMap = new HashMap<String,StaticResource>();
	
	
	public StaticResource getResourceContent(String key)
	{
		return staticMap.get(key);
	}
	
	public StaticContentCache()
	{
		File file = new File("//usr//yixing//static");
//		File file = new File("D://static");
		System.out.println(file.getAbsolutePath());
		if (file.exists() && file.isDirectory())
		{
			File[] files = file.listFiles();
			for (File cfile : files)
			{
				String key = cfile.getName();
				byte[] value = getFileContent(cfile);
				StaticResource resource = new StaticResource();
				resource.setContent(value);
				resource.setLastModifyDate(new Date(cfile.lastModified()));
				resource.setName(key);
				staticMap.put(key, resource);
			}
		}
	}

	private byte[] getFileContent(File file) 
	{
		ByteBuf bb = Unpooled.buffer((int)file.length());
        InputStream in = null;
        try {
            System.out.println("以字节为单位读取文件内容，一次读一个字节：");
            // 一次读一个字节
            in = new FileInputStream(file);
            int tempbyte;
            while ((tempbyte = in.read()) != -1) {
                System.out.write(tempbyte);
                bb.writeByte(tempbyte);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
		return bb.array();
	}
}
